<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" :title="$t('stockManage.pageTitle')" rightText="扫描记录"
				scanType="1" @clickRight="clickRight" @clickLeftBack="clickLeftBack"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto-noheight paddingbottom">
				<!-- 页面头部入库单信息 -->
				<view class="card-mini">
					<view class="card-mini-head">
						<view class="title-line"></view>
						{{ $t('stockManage.receiptMaterial') }}
					</view>
					<view class="card-mini-body">
						<view class="card-mini-item">
							<text class="mini-item-title" style="width: 100%;">{{ $t('stockManage.singleReceiving') }}：{{	data.stockDetail.receiptCode}}</text>
						</view>
						<view class="card-mini-item">
							<text class="mini-item-title">{{ $t('stockManage.receivingOrderQty') }}：{{	data.stockDetail.sumQty}}</text>
						</view>
						<view class="card-mini-item">
							<text class="mini-item-title" style="width: 100%;">{{ $t('translationImage.documentationDate')}}：{{ data.stockDetail.receiptDate }}</text>
						</view>
						<view class="card-mini-item">
							<text class="mini-item-title">{{ $t('stockManage.storageQty') }}：{{	data.stockDetail.sumInstockQty}}</text>
						</view>
						<view class="card-mini-item">
							<view class="mini-item-50">
								<text class="mini-item-title">{{ $t('stockManage.stayPointQty') }}：</text> {{	data.stockDetail.unPointNum}}
							</view>
							<view class="mini-item-50">
								<text class="mini-item-title">{{ $t('distributedEnter.scannedQuantity') }}：</text> {{	data.stockDetail.currentScanSumNum}}
							</view>
						</view>
						<view class="card-mini-item">
							<view class="mini-item-50">
								<text class="mini-item-title">{{ $t('stockManage.giveQty') }}：</text>{{	data.stockDetail.giftNum}}
							</view>
						</view>
						<view class="card-mini-item">
							<text class="mini-item-title" style="width: 100%;">{{ $t('locationBarcodeInfo.contractNo') }}：{{data.stockDetail.contractNumber}}</text>
						</view>
					</view>
				</view>
				<!-- 表单填写区域 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('hardware.warehousingInput') }}
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{ $t('pageTranslation.brand') }}：</text>
						<clearChooseBox style="text-align: right;" :candidates="data.brandList"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" :isJSON="true" keyName="brandName"
							v-model="data.brandName" @select="brandCodeSelect">
						</clearChooseBox>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('pageTranslation.batchNo')
						}}：</text>
						<input style="margin: 8rpx 0;text-align: right;" class="gui-form-input" v-model="data.batchNumber"
							:placeholder="$t('JsInternational.enterBatch')" />
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue" @blur="data.focus=true"
							:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('stockManage.purposeWarehouse')
						}}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.PDATransferIntoList"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="value"
							v-model="data.dicItemByCode">
						</superweiCombox>
					</view>
					<!-- <view class="custom-card-itemTwo">
						<text class="item-info-title"><text
								class="required-color">*</text>{{$t('stockManage.purposeSeat')}}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.warehouseCodeList"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" :emptyTips="$t('pageTranslation.plsChooseDes')"
							keyName="locationCode" keyName1="surplusCapacity" :showType="$t('pageTranslation.volumeOfLocation')"
							:showTitleType="$t('distributedOut.location')" v-model="data.warehouseCode"
							@select="warehouseCodeListSelect">
						</superweiCombox>
					</view> -->
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('warehousing.libraryBitCode')
						}}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.locationCode"
							:placeholder="$t('warehousing.scanLocation')" @confirm="confirmLocation"
							@iconClick="iconClickLocation" :focus="data.focus" @focus="data.focus=true">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('stockManage.purposeSeat')
						}}：</text>
						<storageBin :ignoreLocationCode="data.ignoreLocationCode" v-model="data.locationId"
							:locationList="data.locationList" class="gui-text-right"
							requestUrl="/wms/wmsLocationCapacity/getLocationByWarehouseCodeForCCP"
							:requestParam="data.requestParam" :locationUseList="data.locationUseList" @setClick="getClick">
						</storageBin>
					</view>

				</view>
				<!-- 当前扫描条码 -->
				<view v-if="data.currentScanInfo" class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedOut.barcode') }}：</text>{{data.currentScanInfo.barcode}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{data.currentScanInfo.materialCode}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName')}}：</text>{{ data.currentScanInfo.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec')}}：</text>{{ data.currentScanInfo.materialSpec }}
								</view>
								
								<view class="custom-card-itemOne" style="text-align: left;">
									<view class="card-item-50" >
										<text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{data.currentScanInfo.currentQty}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{data.currentScanInfo.unit}}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('stockManage.receiptMaterial')
					}}</text>
					<view class="gui-title-line"></view>
				</view>
				<uni-card class="element-auto gui-margin-top card-my">
					<view class="element-auto" style="height: 300rpx">
						<zb-table :columns="data.column" :stripe="true" @rowClick="rowClick" :border="true"
							:cell-style="cellStyle" :cell-header-style="cellHeaderStyle" :data="data.wmsReceiptDs"
							@customLook="customBtnFn"></zb-table>
					</view>
				</uni-card>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommitClick">
						{{ $t('stockManage.generate') }}
					</view>
				</view>
			</view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" type="center">
				<view class="input-dialog-box" style="padding: 40rpx;border-radius: 22rpx;width: 600rpx;">
					<uni-icons class="popup-close-icons" type="closeempty" color="#9C9C9C" size="26"
						@click="closePopup"></uni-icons>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{data.wmsReceiptDsInfo.materialCode}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{data.wmsReceiptDsInfo.materialName}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialQty') }}：</text>{{data.wmsReceiptDsInfo.qty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{data.wmsReceiptDsInfo.materialSpec}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{data.wmsReceiptDsInfo.unit}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('translationImage.totalDocuments') }}：</text>{{data.wmsReceiptDsInfo.orderQty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.scannedQuantity') }}：</text>{{data.wmsReceiptDsInfo.scanNum}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('hardware.inventoryQuantity') }}：</text>{{data.wmsReceiptDsInfo.instockQty}}
					</view>
					<view class="gui-form-item" style="color: #dd524d;">
						<text>{{ $t('stockManage.giveQty') }}：</text>
						<view>
							<input type="number" style="margin: 8rpx 0;" disabled class="gui-form-input"
								v-model="data.giveNumber" name="name1" :placeholder="$t('translationImage.pleaseInput')" />
						</view>
					</view>
				</view>
			</uni-popup>
			<!-- 页面弹窗 -->
			<uni-popup ref="inputDialog" type="center">
				<view class="input-dialog-box">
					<view v-if="data.scanInfo" class="input-dialog-content">
						<!-- 需要根据条件判断 -->
						<view
							v-if="data.scanInfo.repaetTypeCode != null && data.scanInfo.repaetTypeCode == 'ReceivingForPlay'"
							class="custom-card-title" style="font-size: 0.975rem;">
							<text class="title-line"></text>
							<!-- ReceivingForPlay -->
							{{ $t('translationImage.givingTheMaterial') }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}：{{ data.scanInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}：{{ data.scanInfo.materialName }}
						</view>
						<view class="gui-form-item">
							<text>{{ $t('translationImage.receivingTheNumber') }}：</text>
							<view>
								<input type="number" style="margin: 8rpx 0;" class="gui-form-input"
									v-model="data.scanInfo.currentQty" name="name1"
									:placeholder="$t('distributedEnter.pleaseMaterialQty')" />
							</view>
						</view>
						<view class="gui-form-item" style="font-weight: 600;" v-show="data.showScanCount">
							<text style="color: #dd524d;width: 300rpx;">{{ $t('distributedEnter.scannedQuantity')
							}}：</text>
							<view>
								<input type="number" disabled style="margin: 8rpx 0;" class="gui-form-input"
									v-model="data.scanInfo.currentQty" name="name1"
									:placeholder="$t('hardwareOut.pleaseQty')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>
<script setup>
import { navigate } from '@/utils/routerSkip.js';
import {ref,toRaw,watch,computed,reactive,onMounted} from 'vue';
import { getDataDictionaryFn, sortClass, pitchOnFn } from '@/utils/index.js'
import tableColor from '@/hooks/tableColor.js';
import storageBin from '@/components/storageBin.vue'
import superweiCombox from '@/components/superweiCombox';
import clearChooseBox from '@/components/clearChooseBox.vue'
import pdaScan from '@/hooks/pdaScan.js'
import graceJS from "@/Grace6/js/grace.js";
import { useStore } from "vuex";
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'
import {findReceiptHById,wmsSelectWmsBarcodeInfo,getLocationByWarehouseCode,wmsCommitReceipt,
	getErpBrand, checkLocation,getLocationCodeByBarcode,isThereALibrary} from '@/api/api.js'
//JS国际化引入
import { useI18n } from 'vue-i18n';
import { onBackPress } from '@dcloudio/uni-app';
const { t } = useI18n();

components: {
	superweiCombox,
		clearChooseBox,
		storageBin
}
const { scan } = pdaScan()
let store = useStore();
let { tableData } = tableColor();
// 接受来自父组件的传参
const props = defineProps({
	id: String,
});
const { cellStyle, cellHeaderStyle } = tableColor();
let popup = ref(null);
let inputDialog = ref(null);
let data = reactive({
	isDunBaoPack:false, //是否是吨包袋物料
	asnNo: '',// 扫码返回 提交使用
	locationId: '',//选中库位的id
	ignoreLocationCode: [], //前端算满的库位
	currentLocationInfo: {}, //当前选中库位信息
	requestParam: {
		warehouseCode: 'RM'
	},
	locationUseList: [],
	calculateData: [],//用于本地的计算data
	scanList: [],// 扫描物料码储存数组
	delScanList: [],//删除扫描的物料码数据用于比对扫描数量和赠送数量
	stockDetail: {
		currentScanSumNum: 0,
		giftNum: 0,
		unPointNum: 0,
	},
	dicItemByCode: '', //目的仓库
	wmsReceiptDs: [],
	value: ['0'],
	staticWarehouseCodeList: [],// 静态库位数组
	warehouseCodeList: [], // 目的库位
	warehouseCode: '',// 选中库位code
	currentScanInfo: undefined, //当前扫描的物料信息
	scanInfo: undefined,// 临时存储数据 用户 扫码展示弹框信息
	PDATransferIntoList: [],//目的仓库
	wmsReceiptDsInfo: {},// 查看选中参数
	id: props.id,// 上级界面传过来的id
	selectedOut: '',
	selectedEnter: '',
	scanValue: '',
	giveNumber: undefined, //赠送数量
	brandList: [],// 品牌列表
	brandName: '',// 品牌名称
	brandCode: '',// 品牌code
	batchNumber: '1',// 批号
	showScanCount: true, //展示扫描的数量
	column: [{
		name: 'age',
		type: 'ailibtn',
		label: t('translationImage.operation'),
		scanValue: '',
		fixed: true,
		width: 80,
	},
	{
		name: 'materialCode',
		label: t('distributedEnter.materialCode'),
		width: 100,
		fixed: true,
		emptyString: '--'
	},
	{
		name: 'materialName',
		label: t('distributedEnter.materialName'),
	},
	{
		name: 'qty',
		label: t('distributedEnter.materialQty')
	},
	{
		name: 'materialSpec',
		label: t('distributedEnter.materialSpec')
	},
	{
		name: 'unit',
		label: t('distributedEnter.uom'),
	},
	{
		name: 'qty',
		label: t('hardware.receiptsQty')
	},
	{
		name: 'scanNum',
		label: t('distributedEnter.scannedQuantity')
	},
	{
		name: 'instockQty',
		label: t('hardware.inventoryQuantity')
	}, {
		name: 'giveNum',
		label: t('stockManage.giveQty')
	},
	],
	locationCode: '',
	position: '',
	locationList: [],
	isThereALibrary: false,
	focus:false
})
onMounted(() => {
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (itme) => {
		console.log('获取到的code：' + itme.code)
		if(!data.focus){
			getCode(itme.code, 'pda')
		}
		if(data.focus){
			getCodeLocation(itme.code, 'pda')
		}
	})
	getRequestData()
	
})

onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					store.dispatch('stockManage/resetSubmittedWmsScanList', data.id)
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.clearedIfReturned'),
		success: function (res) {
			if (res.confirm) {
				store.dispatch('stockManage/resetSubmittedWmsScanList', data.id)
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
const getInitData = async () => {
	// 查询目的仓库
	 let  storeList = await getDataDictionaryFn('PDATransferInto')
	if(data.isDunBaoPack)  //吨包袋
	{
		let tepSelect1=toRaw(storeList).filter(x => x.value == 'FS')
		data.PDATransferIntoList=tepSelect1
		data.selectedEnter = tepSelect1[0].text
		data.selectedOut = tepSelect1[0].text
		data.dicItemByCode = tepSelect1[0].value
		// getWarehouseCode(tepSelect1[0].value);
		data.requestParam.warehouseCode = tepSelect1[0].value
	}
	else{
		let tepSelect1 = pitchOnFn(storeList)
		data.PDATransferIntoList=tepSelect1
		data.selectedEnter = tepSelect1[0].text
		data.selectedOut = tepSelect1[0].text
		data.dicItemByCode = tepSelect1[0].value
		// getWarehouseCode(tepSelect1[0].value);
		data.requestParam.warehouseCode = tepSelect1[0].value
	}
	

	// 查询品牌列表
	let res = await getErpBrand({})
	if (res.status == 200) {
		res.data.map((item) => {
			item.brandName = `${item.brandName}-${item.brandCode}`
		})
		data.brandList = res.data
	} else {
		uni.showToast({ title: res.message, icon: "none" });
	}

}
const brandCodeSelect = (e) => {
	data.brandCode = e.brandCode
}
// 获取选中的库位id
const getClick = (x) => {
	console.log(x, x.locationCode)
	data.currentLocationInfo = x;
	data.locationId = x.locationCode;
}
// 计算库位逻辑
const calculateLocationCode = (newVal) => {
	let tepData = toRaw(newVal)
	// 先清空,后续追加
	data.locationUseList.forEach(l => {
		l.barcodeList = []
	})
	// 追加
	tepData[0].arr.forEach(x => {	
		data.locationUseList.forEach(k => {
			if ((x.locationCode||x.locationName) == k.locationCode) {
				k.barcodeList.push(x.barcode)
				k.surplusCapacity = k.currentCapacity - k.barcodeList.length
			}
		})
	})
	//算满库位变量置空
	data.ignoreLocationCode = []
	// 把前端预算容量算出为0的库位抽出
	data.locationUseList.forEach(x => {
		if (x.surplusCapacity == 0) {
			data.ignoreLocationCode.push(x.locationCode)
		}
	})
	console.log(data.locationUseList, 'data.locationUseList')
	console.log(data.ignoreLocationCode, 'data.ignoreLocationCode')
}

// 查询初始化数据
const getRequestData = () => {
	let parmes = {
		id: data.id
	}
	findReceiptHById(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '来料入库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_LOOK
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			let stockDetail = res.data
			let unPointNum = Number(stockDetail.sumQty) - Number(stockDetail.sumInstockQty)
			data.stockDetail = stockDetail
			data.stockDetail.currentScanSumNum = 0
			data.stockDetail.unPointNum = unPointNum
			// 拼接合同单号
			let a=''
			data.stockDetail.wmsReceiptDs.forEach(item=>{
				if(!(a.includes(item.contractNumber))){
					a=a+item.contractNumber+','
				}
			})
			data.stockDetail.contractNumber=a.slice(0, -1)
			// 获取展示收料单信息
			data.wmsReceiptDs = res.data.wmsReceiptDs
			if(data.wmsReceiptDs!=null&&data.wmsReceiptDs.length)
			{   
				//吨包袋入库到粉碎仓
				if(data.wmsReceiptDs.some(h=>h.materialCode=="11JBAF01"))
				{
					data.isDunBaoPack=true
				}
				else{
					data.isDunBaoPack=false
				}
			}
			getInitData()
			watcShowscanList()
		}
	})
}

// 用户调起相机扫码
const iconClickLocation = async (type) => {
	if (type === 'suffix') {
		let code = await scan()
		getCodeLocation(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirmLocation = () => {
	getCodeLocation(data.locationCode, 'keydown')
}

// 获取code
const getCodeLocation = (code, type) => {
	data.locationCode = code
	var parmes = {
		warehouseCode: data.dicItemByCode,
		locationCode: code,
	}
	checkLocation(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '来料入库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200 && res.data.residualCapacity != 0) {
			// console.log(res.data)
			data.currentLocationInfo = res.data;
			data.locationId = res.data.locationCode;
		} else if (res.status == 200 && res.data.residualCapacity == 0) {
			uni.showToast({ title: t('warehousing.capacityLibrary'), icon: "none" });
		}
		else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}

// 用户调起相机扫码
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = async(code, type) => {
	// 如果扫描记录为空执行
	// if (!data.scanList.length) {
	// 	// console.log(data.scanList.length)
	// 	let barcode = code
	// 	getLocationCodeByBarcode({ barcode }).then(res => {
	// 		// data.locationId=res.data[0].locationCode
	// 		data.locationList = res.data
	// 		data.position = res.data[0].position
	// 	})
	// } else {
	// 	await isThereALibrary({ barcode: code, position: data.position }).then(res => {
	// 		if (res.data) {
	// 			data.isThereALibrary = false
	// 		} else {
	// 			data.isThereALibrary = true
	// 		}
	// 	})
	// }
	// if(data.isThereALibrary){
	// 	uni.showToast({
	// 				title: t('warehousing.materialsCannotB'),
	// 				icon: 'none'
	// 			})
	// 	return
	// }
	if (data.stockDetail.unPointNum == 0) {
		uni.showToast({ title: t('JsInternational.qtyPending'), icon: "none" });
		return
	}

	// 判断当前用户选择的库位有没有容量
	if (data.ignoreLocationCode.includes(data.locationId)) {
		uni.showToast({
			title: t('JsInternational.volumn'),
			icon: 'none'
		})
		return
	}
	if (!data.batchNumber.length) {
		uni.showToast({ title: t('JsInternational.enterBatch'), icon: "none" });
		return
	}
	let repetitionBool = false // 是否重复标识
	let tepList = toRaw(data.scanList)
	tepList.forEach(x => {
		x.arr.forEach(k => {
			if (code == k.barcode) {
				repetitionBool = true
				uni.showToast({ title: t('JsInternational.scanInputBarcode'), icon: "none" });
				return
			}
		})
	});
	if (repetitionBool) return // 重复扫描 不执行以下流程
	data.scanValue = code
	var parmes = {
		isSp: 0,
		barcode: code,
		selectType: 'incomingMaterial',
		receiptId: data.id,
	}
	wmsSelectWmsBarcodeInfo(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '来料入库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			let bool = data.wmsReceiptDs.some((item) => {
				return item.materialCode == res.data.materialCode
			})
			if (!bool) {
				uni.showToast({ title: t('materials.materialIsNot'), icon: "none" });
				return
			}
			data.scanInfo = res.data
			console.log(data.scanInfo)
			data.scanInfo.batchNumber = data.batchNumber
			data.scanInfo.brandCode = data.brandCode
			if (data.scanInfo.barcode == "COVERPLATECARD-CHINA"
				|| data.scanInfo.barcode == "PALLETCARD-CHINA"
				|| data.scanInfo.barcode == "COVERPLATECARD-USA"
				|| data.scanInfo.barcode == "PALLETCARD-USA") {
				data.scanInfo.currentQty = 0
				data.showScanCount = false
			}
			else {
				data.showScanCount = true

			}
			inputDialog.value.open()
			// 筛选出和当前扫码一直的物料并提位  wmsReceiptDs
			if (data.wmsReceiptDs.length && data.wmsReceiptDs.length != 1) {
				for (var i = 0; i < data.wmsReceiptDs.length; i++) {
					var item = {}
					if (data.wmsReceiptDs[i].materialCode === res.data.materialCode) {
						item = data.wmsReceiptDs[i]
						data.wmsReceiptDs.splice(i, 1);
						data.wmsReceiptDs.unshift(item)
						break;
					}
				}
			}
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}
// fqc扫描条码
data.scanList = computed(() => {
	return store.state.stockManage.wmsScanList
})
// 剥离计算方法 用于方便调用
const watcShowscanList = () => {
	// 第一次判断  判断当前数组是否有值
	let newVal = data.scanList
	if (newVal.length == 0) {
		data.currentScanInfo = undefined
	}
	let indexArr = newVal.filter(x => x.storeId == data.id)
	let filtNewVal = indexArr.length == 0 ? [] : indexArr[0].arr
	// 第二次为空判断  判断根据当前的storeId是否能取到值
	if (!filtNewVal.length) {
		data.currentScanInfo = undefined
	}
	data.calculateData = filtNewVal
	let sumCurrentQty = 0
	let sumSendNum = 0
	filtNewVal.forEach(item => {
		sumCurrentQty += item.currentQty
		if (item.repaetTypeCode != null && item.repaetTypeCode == 'ReceivingForPlay') {
			sumSendNum += item.currentQty
		}
	});
	// 遍历数组 查询当前扫描的物料信息 与当前的收集单信息相比对进行重新赋值
	data.wmsReceiptDs.forEach(element => {
		let scanNum = 0
		let giveNum = 0
		filtNewVal.forEach(item => {
			// 根据当前扫描的materialCode物料code  查询到相对应收集单信息
			if (element.materialCode == item.materialCode) {
				scanNum = scanNum + Number(item.currentQty)
				// 判断当前是否是赠送扫描
				if (item.repaetTypeCode && item.repaetTypeCode == 'ReceivingForPlay') {
					giveNum = giveNum + Number(item.currentQty)
				}
			}
		});
		element.giveNum = giveNum //赠送数量等同于物料数量
		element.scanNum = scanNum //物料数量
	});
	data.stockDetail.currentScanSumNum = sumCurrentQty
	data.stockDetail.unPointNum = (+data.stockDetail.sumQty - Number(data.stockDetail.currentScanSumNum) - Number(data.stockDetail.sumInstockQty)).toFixed(4)
}
//把扫描条码变为物料集合的二维数组
watch(() => data.scanList, (newVal) => {
	console.log('data.scanList', data.scanList)
	console.log('newVal', newVal)
	watcShowscanList()
	calculateLocationCode(newVal)
}, {
	immediate: true,
	deep: true
});
const clickRight = () => {
	navigate({
		url: `/pages/materialManage/stockManageRecord?id=${data.id}`
	})
}
// 列事件
const rowClick = (e) => {
	console.log(e)
}
// 查看
const customBtnFn = (item, index) => {
	data.wmsReceiptDsInfo = item
	data.giveNumber = item.giveNum
	try {
		let inputParameter = JSON.stringify(item)
		let returnParameter = '无'
		let operationPicture = '来料入库'
		let callInterface = '无'
		let opertionParmes = {
			inputParameter,
			returnParameter,
			operationPicture,
			callInterface,
			responseCode: '无',//返回状态
			errorMessage: '无',//错误信息
			isPass: 'Y',//是否成功 Y N
			operationType: OPERATION_LOOK
		}
		basPdaOperationLogFn(opertionParmes)
	} catch (error) {
	}
	popup.value.open()
}
const closePopup = () => {
	popup.value.close()
}
const cancelFn = () => {
	inputDialog.value.close()
	data.scanInfo = undefined
	popup.value.close()
}
const scanConfirmFn = () => {
	let scanInfo = data.scanInfo
	scanInfo.currentQty = Number(scanInfo.currentQty)
	if (scanInfo.currentQty <= 0) {
		uni.showToast({ title: t('JsInternational.scanSubmit'), icon: "none" });
		return
	} else {
		let wmsqty = 0
		let text = ''
		let sumSendm = 0 //当前扫码的总赠送数量
		// 计算当前物料剩余的扫描容量
		data.wmsReceiptDs.forEach((item) => {
			sumSendm += Number(item.giveNum)
			if (item.materialCode == scanInfo.materialCode) {
				console.log(item, '------item------')
				wmsqty = Number(item.qty) - Number(item.scanNum) - Number(item.instockQty)
				wmsqty=parseFloat(wmsqty.toFixed(4)) 
				text = item.materialName
			}
		})
		// 当前为赠送物料
		if (scanInfo.repaetTypeCode != null && scanInfo.repaetTypeCode == 'ReceivingForPlay') {
			if (Number(data.scanInfo.currentQty) > Number(data.stockDetail.giftNum)) {
				uni.showToast({ title: t('pageTranslation.currentQtyOfGiveAway'), icon: "none" });
				return
			}
			// 拿到前物料中赠送数量 + 当前赠数量进行比对 超出提示
			if (sumSendm + Number(data.scanInfo.currentQty) > Number(data.stockDetail.giftNum)) {
				uni.showToast({ title: t('pageTranslation.currentQtyOfGiveAway'), icon: "none" });
				return
			}
		}
		//判断当前物料数量 是否超出总收料单总数
		if (Number(scanInfo.currentQty) > data.stockDetail.sumQty) {
			uni.showToast({ title: t('JsInternational.stockinQty'), icon: "none" });
			return
		}
		
		if (wmsqty - Number(scanInfo.currentQty) < 0) {
			uni.showToast({ title: t('JsInternational.Scanning') + `${text}` + t('JsInternational.qtyGreaterThan'), icon: "none" });
			return
		}
		// 计算待点数量  并且判断扫描数量是否超出收料单总数
		let unPointNum = Number(data.stockDetail.currentScanSumNum) + Number(scanInfo.currentQty) + Number(data.stockDetail.sumInstockQty)

		if (Number(unPointNum.toFixed(4)) >data.stockDetail.sumQty) {
			uni.showToast({ title: t('pageTranslation.scannedQtyCant'), icon: "none" });
			return
		}
		let isTrue = data.locationUseList.some(x => x.locationCode === data.locationId)

		if (!isTrue) {
			data.locationUseList.push({
				locationCode: data.currentLocationInfo.locationCode, //库位code
				surplusCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端告诉前端容量
				barcodeList: [], //当前库位本次扫描绑定的barcode条码集合
				currentCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端容量减去本次扫描绑定条码的剩余容量  前端预算容量
			})
		}
		data.currentScanInfo = scanInfo
		data.currentScanInfo.warehouseCode = data.dicItemByCode
		data.currentScanInfo.locationCode = data.locationId // 把当前的locationCode 库位标识赋值给保存的扫码信息 用于监听做比对
		data.currentScanInfo.storeId = data.id // 保存id 用户区分是那个收料单进来的数据
		store.dispatch('stockManage/SetWmsScanList', data.currentScanInfo)
		inputDialog.value.close();
	}
}
// 提交来料入库
const handelCommitClick = () => {
	if(data.locationId==''){
		uni.showToast({ title: t('Common.pleaseSelectLocation'), icon: "none" });
		return
	}
	if (data.locationCode == '') {
		data.locationCode = data.locationId
	}
	if (data.calculateData.length == 0) {
		uni.showToast({ title: t('stockManage.pleaseScanCode'), icon: "none" });
		return
	}
	let tepData = toRaw(data.calculateData)
	let list = sortClass(tepData)
	let tepList = []
	list.forEach(x => {
		let item = {
			materialCode: '',//物料code
			barcodeInfoVos: [], //条码信息
		}
		x.forEach(k => {
			let dict = {
				qty: 0,
			}
			console.log(k)
			item.materialCode = k.materialCode
			dict.barcode = k.barcode//条码barcode
			dict.id = k.id//条码id
			dict.asnNo = k.asnNo || ''
			dict.batchNumber = k.batchNumber
			dict.brandCode = k.brandCode
			dict.qty += Number(k.currentQty)//用户输入的qty
			dict.warehouseCode = k.warehouseCode //仓库code
			dict.locationCode = k.locationCode==''?data.locationId:k.locationCode //库位code
			item.barcodeInfoVos.push(dict)
		})
		tepList.push(item)
	});
	var parmes = {
		id: data.id, // 收料单id
		isSp: 0,//区分是五金来时来料
		receiptCode: data.stockDetail.receiptCode, //收料单code
		receiptBarcodes: tepList // 条码信息
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	wmsCommitReceipt(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '来料入库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			//删除已提交的数据
			store.dispatch('stockManage/resetSubmittedWmsScanList', data.id)
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: "none",
				duration: 2000,
				complete: function (res) {
					// 返还上一个页面
					setTimeout(function () {
						uni.navigateBack({
							delta: 1
						});
					}, 1000);
				}
			});

		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})

}
</script>

<style lang="scss" scoped>
.gui-form-input {
	font-size: 26rpx !important;
}
</style>
